Reaccionar Advertencia eliminar Advertencia: cada niño en una lista debe tener una "clave" única.
Me gustaría eliminar la 「Advertencia: cada niño en una lista debe tener un accesorio de "clave" único.」
El código es el siguiente
import { useState } from "react"; const SIZE_ARRAY = [ { label: "Small", value: "sm" }, { label: "Medium", value: "md" }, { label: "Large", value: "lg" } ]; const DEVICE_ARRAY = [ { deviceLabel: "PC", deviceValue: "pc" }, { deviceLabel: "Tablet", deviceValue: "tablet" }, { deviceLabel: "Mobile", deviceValue: "mobile" } ]; export default function SampleLoop() { const [option, setOption] = useState(); return ( <> <ul> {SIZE_ARRAY.map((size) => { const { label, value } = size; return ( <li key={label}> <span>Margin : {label}</span> {DEVICE_ARRAY.map((device) => { const { deviceLabel, deviceValue } = device; return ( <> <input key={deviceLabel} onChange={(newValue) => { setOption({ ...option, margin_size: { ...option.margin_size, [value]: { ...option.margin_size[value], [deviceValue]: newValue } } }); }} /> </> ); })} </li> ); })} </ul> </> ); }Es una forma anidada de dos bucles.
¿Hay una posición diferente para colocar la LLAVE?
Aquí:
{DEVICE_ARRAY.map((device) => { const { deviceLabel, deviceValue } = device; return ( <> <input key={deviceLabel} onChange={(newValue) => { setOption({ ...option, margin_size: { ...option.margin_size, [value]: { ...option.margin_size[value], [deviceValue]: newValue } } }); }} /> </> ); })} El "elemento raíz" de cada hijo es </> , es decir, <Fragment/> , no <input/> . Por lo tanto, debe definir la clave en el primero. Aunque, francamente, no necesita ese Fragment aquí a menos que haya omitido algunos componentes en su código publicado.
Por cierto, no puede usar la abreviatura de fragmento si especifica algún accesorio en él. es decir, esto no funciona:
< key={deviceLabel}> </>En su lugar, haz esto
<Fragment key={deviceLabel}> </Fragment>Eliminar el fragmento redundante alrededor <input>
import { useState } from "react"; const SIZE_ARRAY = [ { label: "Small", value: "sm" }, { label: "Medium", value: "md" }, { label: "Large", value: "lg" } ]; const DEVICE_ARRAY = [ { deviceLabel: "PC", deviceValue: "pc" }, { deviceLabel: "Tablet", deviceValue: "tablet" }, { deviceLabel: "Mobile", deviceValue: "mobile" } ]; export default function SampleLoop() { const [option, setOption] = useState(); return ( <ul> {SIZE_ARRAY.map((size) => { const { label, value } = size; return ( <li key={label}> <span>Margin : {label}</span> {DEVICE_ARRAY.map((device) => { const { deviceLabel, deviceValue } = device; return ( <input key={deviceLabel} onChange={(newValue) => { setOption({ ...option, margin_size: { ...option.margin_size, [value]: { ...option.margin_size[value], [deviceValue]: newValue } } }); }} /> ); })} </li> ); })} </ul> ); }